package com.gack.business.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.gack.business.dao.StoreSupportFacityAndSupportServiceDao;
import com.gack.business.model.Order;
import com.gack.business.model.StoreAttention;
import com.gack.business.model.StoreUniteInfo;
import com.gack.business.model.User;
import com.gack.business.model.VideoStores;
import com.gack.business.repository.OrderRepository;
import com.gack.business.repository.StoreAttentionRepository;
import com.gack.business.repository.StoreUniteInfoRepository;
import com.gack.business.repository.UserRepository;
import com.gack.business.repository.VideoStoresRepository;
import com.gack.helper.common.AjaxJson;

import io.swagger.annotations.ApiOperation;

@Service
public class VideoStoresService {
	
	private static final double EARTH_RADIUS = 6378137;  
	
	@Autowired
	private  VideoStoresRepository   videoStoresRepository;
	@Autowired
	private OrderRepository orderRepository;
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private StoreUniteInfoRepository storeUniteInfoRepository;
	@Autowired
	private StoreSupportFacityAndSupportServiceDao facityAndServiceDao;
	@Autowired
	private StoreAttentionRepository attentionRepository;
	
	
	
	
	  
	    private static double rad(double d)  
	    {  
	        return d * Math.PI / 180.0;  
	    }  
	  
	    /** 
	     * 传递经纬度返回差距 单位（米） 
	     * @param lat1 经度1 
	     * @param lng1 纬度1 
	     * @param lat2 经度2 
	     * @param lng2 纬度2 
	     * @return 
	     */  
	    public static double getDistance(double lat1, double lng1, double lat2, double lng2)  
	    {  
	        double radLat1 = rad(lat1);  
	        double radLat2 = rad(lat2);  
	        double a = radLat1 - radLat2;  
	        double b = rad(lng1) - rad(lng2);  
	        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +  
	                Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));  
	        s = s * EARTH_RADIUS;  
	        s = Math.round(s * 10000) / 10000;  
	        return s;  
	    }  
	
	    
	    //通过当前用户的经纬度，查询附近的店铺
	    
	    /**
	     *   SQL语句：（传入用户当前距离：蓝色为纬度，红色为经度）

			 SELECT *,SQRT(
			
			    POW(111.2 * (lat - 40.0844020000), 2) +
			
			    POW(111.2 * (116.3483150000 - lng) * COS(lat / 57.3), 2)) AS distance
			
			 FROM map HAVING distance < 25 ORDER BY distance;
			
			  得到结果：distance字段为 当前位置 到 所有店铺 的直线距离，单位km
	     */
	    
	    
	    /**
	     * 
	     * @param longitude   当前用户位置经度
	     * @param latitude    当前用户位置纬度    
	     * @return
	     */
	    
	    @ApiOperation(value = "查找附近门店列表")
		@RequestMapping(value="findNearStores",method = RequestMethod.POST)
		public AjaxJson findNearStores(String longitude,String latitude,String id){
			AjaxJson ajaxJson=new AjaxJson();
			try {
				Map<String,Object> resultMap = new HashMap<>();
				Order order = null;
				Integer distance = null;
				List<VideoStores> stores = null;
				Integer total = null;
				if((longitude != null && !longitude.equals("")) && (latitude != null && !latitude.equals(""))){
					StoreUniteInfo storeUniteInfo = storeUniteInfoRepository.findUniteInfoByKey("distance");
					if(storeUniteInfo != null && storeUniteInfo.getUniteValue() != null){
						try{
							distance = Integer.valueOf(storeUniteInfo.getUniteValue().trim());
							stores = videoStoresRepository.getAllCanUseStoresByDistance(longitude, latitude, distance);
							total = videoStoresRepository.getCountOfStoresCanUseByDistance(longitude, latitude, distance);
						}catch (Exception e) {
							e.printStackTrace();
							stores = videoStoresRepository.getAllCanUseStores();
							total = videoStoresRepository.getCountOfStoresCanUse();
						}
					}
				}else{
					stores = videoStoresRepository.getAllCanUseStores();
					total = videoStoresRepository.getCountOfStoresCanUse();
				}
				if(id != null && !id.equals("")){
					User user = userRepository.findOne(id);
					if(user != null){
						List<Order> orders = orderRepository.getUserUsingOrReservedOrder(id);
						if(orders != null && orders.size() > 0){
							order = orders.get(0);
						}
					}
				}
				String reservation = "0";
				Date now = new Date();
				for(VideoStores store : stores){
					//不营业 门店状态为2（状态值暂定）
					if(store.getIsUse() == 2){
						store.setStatus(2);
					}
					//超过预定营业时间  状态为2（状态值暂定）
					try{
						if(!(getHMS(store.getStarttime()) < getHMS(now) && getHMS(now) < getHMS(store.getEndtime()))){
							store.setStatus(2);
						}
					}catch (Exception e) {
						e.printStackTrace();
					}
					if(order != null && store.getId().equals(order.getStoreId())){
						if(order.getStatus().equals("1")){
							store.setStatus(3);
							reservation = "1";
						}else if(order.getStatus().equals("4")){
							store.setStatus(4);
							reservation = "1";
						}else if(order.getStatus().equals("5") || order.getStatus().equals("6") || order.getStatus().equals("7")){
							reservation = "2";
						}
						break;
					}
					
				}
				resultMap.put("reservation", reservation);
				resultMap.put("stores", stores);
				resultMap.put("total", total);
				ajaxJson.setSuccess(true).setStatus(200).setMsg("操作成功").setData(resultMap);
			} catch (Exception e) {
				ajaxJson.setSuccess(false).setStatus(500).setMsg("操作失败").setData("error");
			}
			return ajaxJson;
		}
		
	    
	    /**
	     * 
	    * @Title: findStoreInfo 
	    * @Description: TODO(获取门店详情) 
	    * @param @param id
	    * @param @return    入参
	    * @return AjaxJson    返回类型
	    * @author （ZhangXinYu） 
	    * @throws
	    * @date 2018年3月21日 下午3:26:08 
	    * @version V1.0
	     */
	    public AjaxJson findStoreInfo(String id){
	    	AjaxJson ajaxJson=new AjaxJson();
			try {
				VideoStores stores = videoStoresRepository.findOne(id);
				if(stores != null) {
					stores.setFacities(facityAndServiceDao.facities(stores.getId()));
					stores.setServices(facityAndServiceDao.services(stores.getId()));
					List<StoreAttention> attentions = attentionRepository.findAll();
					if(attentions != null && attentions.size() > 0){
						stores.setAttention(attentions.get(0).getAttention());
					}else{
						stores.setAttention(null);
					}
				}
				ajaxJson.setSuccess(true).setStatus(200).setMsg("操作成功").setData(stores);
			} catch (Exception e) {
				ajaxJson.setSuccess(false).setStatus(500).setMsg("操作失败").setData("error");
			}
			return ajaxJson;
	    }
	    
	    private long getHMS(Date d) throws Exception{
	    	DateFormat df = new SimpleDateFormat("hh:MM:ss");
	    	java.util.Date date = df.parse(df.format(d));
	    	Calendar cal = Calendar.getInstance();
	    	cal.setTime(date);
	    	long timestamp = cal.getTimeInMillis();
	    	return timestamp;
	    }

}
